import java.net.*;
import java.io.*;
import java.util.*;

public class HTTPCmdRead extends Thread {
   private HTTPRequest request = null;
   private Connection  client;
   private CmdQueue    queue;
   private Command     myCommand;
   
   public HTTPCmdRead(Connection client, CmdQueue  c) {      
      this.client = client;
	this.queue  = c;
	myCommand   = new Command();

      try {
         request = new HTTPRequest(client.getInputStream());
      } catch (NullPointerException e) {
         System.out.println(e);
      }
      
      setDaemon(true);
   }
   
   public void run() {
      Hashtable params;
      String    c, i, l, s;
	int 	    cmd = Command.cmdNULL;
      
	// Let the httprequest object read the instream and then parse it.
	// Stuff into a command an enqueue it.
      try {	
	   request.read();

         params = CGI.splitVars(request.content());

         c = (String) params.get("command");
         i = (String) params.get("integer");
         l = (String) params.get("long");
         s = (String) params.get("string");

	   if (c.equals(Command.cmdTextSTOP)) cmd = Command.cmdSTOP;
	   else if (c.equals(Command.cmdTextPAUSE)) cmd = Command.cmdPAUSE;
	   else if (c.equals(Command.cmdTextNEW))   cmd = Command.cmdNEW;
	   else if (c.equals(Command.cmdTextTARGET)) cmd = Command.cmdTARGET;
	   else if (c.equals(Command.cmdTextGETLOG)) cmd = Command.cmdGETLOG;
	   else if (c.equals(Command.cmdTextGO))     cmd = Command.cmdGO;
	   else if (c.equals(Command.cmdTextPING))   cmd = Command.cmdPING;
	   else cmd = Command.cmdNULL;


	   myCommand.setCommand(cmd,Integer.parseInt(i),Long.parseLong(l),s,
				      client,request.protocol());	

	   queue.putCommand(myCommand);
          
      } catch (Exception e) {
			
	   // Something REAL bad happened.  Return something to the sender, and
	   // let the connection die.  Do not enqueue a command.	
	   myCommand.setCommand(0,0,0," ",client,request.protocol());	  
         StringBuffer r = new StringBuffer();
	   r.append("<HTML><HEAD><TITLE>"+Dispatcher.wordError+"</TITLE></HEAD><BODY><H2>MALFORMED OR CORRUPTED COMMAND");
	   r.append("</H2><PRE>Exception = " +  e.getMessage() +
				 "\n" + e.toString() + "</PRE></BODY></HTML>");
	   myCommand.respond(r.toString());
         client.close();
	}
   }

}

      

   
         
